<!DOCTYPE html>
<html>
<head>
    <title>常量属性生成</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<style>
    input, textarea {
        width: 700px;
    }

    #result {
        height: 500px;
    }
</style>
<body>

<table>
    <tr>
        <td>前缀</td>
        <td>
            <input type="text" id="pre">
        </td>
    </tr>
    <tr>
        <td>内容</td>
        <td>
            <textarea type="text" id="data"></textarea>
        </td>

    </tr>
    <tr>
        <td>结果</td>
        <td>
            <textarea id="result"></textarea>
        </td>
    </tr>

</table>
<button onclick="generate()">生成</button>
<script type="text/javascript">
    function getConstantName(pre,value) {
        value = value.replace(/([A-Z])/g, "_$1");
        value = value.replace(/-/g, "_");
        var key = (pre + "_" + value).toUpperCase()
        return key;
    }
    function preProcess(item) {
        if (item.charAt("'") || item.charAt("\"")) {
            item = item.replace(/\"/g, "");// /g表示使用正则进行全文搜索，全部替换
            item = item.replace(/'/g, "");
        }
        return item;
    }
    function generate() {
        var pre = $('#pre').val();
        var data = $('#data').val();
        var arr = data.split(",");
        var KEY_DEFINE_MAP = {};
        var KEY_FUN_MAP = {};
        var tempFunc = " public function $FUN_NAME($value)\n{\nreturn $this->updateData(self::$FUN_KEY, $value);\n}";

        for (var i = 0; i < arr.length; i++) {
            var item = preProcess(arr[i]);
            var key = getConstantName(pre,item);
            var value = item;
            KEY_DEFINE_MAP[key] = "const " + key + "=\"" + value + "\";";
            var func = tempFunc.replace("$FUN_NAME", value.replace(/-/g, "_"));
            func = func.replace("$FUN_KEY", key);
            KEY_FUN_MAP[key] = func;
        }
        var keyStr = " protected $methods = array(";
        var valueStr = "";
        var functionStr = "";
        // 遍历
        for (var k in KEY_DEFINE_MAP) {
            keyStr += "self::" + k + ",";
            valueStr += KEY_DEFINE_MAP[k] + "\n";
            functionStr += KEY_FUN_MAP[k] + "\n";
        }
        keyStr += ");"
        $('#result').val(keyStr + "\n" + valueStr + "\n" + functionStr);
    }
</script>
</body>
</html>

